﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;

namespace WindowsFormsApplication1
{
    /*
     * MainInterface la class demo giao dien va phan mat truoc
     * cua may bom insulin tu dong
     */

    public partial class MainInterface : Form
    {
        int FocusedLabel = -1; // = 0 la chinh gio, = 1 la chinh phut, 2 la pump insulin
        public bool resetButtonClicked = false; // kiem tra su kien nhan button reset
        bool flag = false; // de xac dinh xem co dung nut setting khong
        public  bool flagTurnOn = false; // kiem tra su kien nhan nut ON/Off

        //Cac Status cua he thong
        private const int NORMAL = 3;
        private const int WARNING = 4;
        private const int ERROR = 5;
        
        private int seconds = 60;//do dem thoi gian

        //Cac doi tuong lien ket luong PumpController vaf Tester
        Thread pumpControllerThread;
        Thread testerThread;

        public MainInterface()
        {
            InitializeComponent();

            // To report progress from the background worker we need to set this property
            backgroundWorker1.WorkerReportsProgress = true;
            // This event will be raised on the worker thread when the worker starts
            backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
            // This event will be raised when we call ReportProgress
            backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
            backgroundWorker1.RunWorkerAsync();

            // Khoi tao cac thong so cho bieu do luong duong trong mau
            chartBloodLevel.ChartAreas[0].AxisX.Maximum = 30;
            chartBloodLevel.ChartAreas[0].AxisX.Minimum = 1;
            chartBloodLevel.ChartAreas[0].AxisX.Interval = 1;
            chartBloodLevel.ChartAreas[0].AxisY.Maximum = 35;
            chartBloodLevel.ChartAreas[0].AxisY.Minimum = 0;
            chartBloodLevel.ChartAreas[0].AxisY.Interval = 5;
            chartBloodLevel.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
            chartBloodLevel.ChartAreas[0].AxisX.Enabled = System.Windows.Forms.DataVisualization.Charting.AxisEnabled.False;
        }

        public void AddPumpControllerThead(ref  Thread threadObj)
        {
            this.pumpControllerThread = threadObj;
        }

        public void AddTesterThread(ref Thread threadObj)
        {
            this.testerThread = threadObj;
        }
        private void ChangeMode()
        {
            if (!groupBoxMainScreen.Enabled)
                return;

            if (UpBtn.Enabled == false)
            {
                modeBtn.Text = "Manual";
                modeNameLbl.Text = "Maunal";
                UpBtn.Enabled = true;
                downBtn.Enabled = true;
                pumpBtn.Enabled = true;
                insulinDoseOption.Visible = true;
                insulinDoseOption.Text = "0";
            }
            else
            {
                modeBtn.Text = "Auto";
                modeNameLbl.Text = "Auto";
                UpBtn.Enabled = false;
                downBtn.Enabled = false;
                pumpBtn.Enabled = false;
                insulinDoseOption.Visible = false;
            }
        }

        private void modeBtn_Click(object sender, EventArgs e)
        {
            if (!flagTurnOn)
                return;

            if (settingBtn.Enabled)
            {
                FocusedLabel = 2;
                ChangeMode();
            }
        }

        System.Windows.Forms.Timer tmr = null;
        private void StartTimer()
        {
            tmr = new System.Windows.Forms.Timer();
            tmr.Interval = 1000;
            TimeSpan ts = DateTime.Now.TimeOfDay;
            DateTime nowTime = new DateTime();
            nowTime = nowTime.Date + ts;
            timeLbl.Text = nowTime.ToShortTimeString();
            tmr.Tick += new EventHandler(tmr_Tick);
            tmr.Enabled = true;
            seconds = 60;
            
        }

        void tmr_Tick(object sender, EventArgs e)
        {
            // lay gia tri phan tram insulin tren progressbar
            int percent = (int)(((double)remainInsulinBar.Value /
                                            (double)remainInsulinBar.Maximum) * 100);

            // ve lai nhan voi mau tuong ung
            if(remainInsulinBar.Value > 10)
             remainInsulinBar.CreateGraphics().DrawString("remain insulin", new Font("Arial", 
                                                            (float)8.25, FontStyle.Regular), Brushes.Black, 
                                                                new PointF(remainInsulinBar.Width / 2 - 45, 
                                                                                remainInsulinBar.Height / 2 - 5));
            else
                remainInsulinBar.CreateGraphics().DrawString("remain insulin", new Font("Arial", 
                                                               (float)8.25, FontStyle.Regular), Brushes.Red, 
                                                                    new PointF(remainInsulinBar.Width / 2 - 45, 
                                                                                remainInsulinBar.Height / 2 - 5));
            if (flag) // button setting da duoc nhan
                return;

            if (seconds > 0)
            {
                seconds--;
                return;
            }
            else
                seconds = 60;

            //thiet dat lai thoi gian tren man hinh
            //
            String[] time= timeLbl.Text.Split(':');
            DateTime s = new DateTime();
            TimeSpan ts;
            int hour = Convert.ToInt16(time[0]);

            if (time[1].Length <= 2)
            {
                int minute = Convert.ToInt16(time[1]) + 1;
                if (minute > 59)
                {
                    minute = 0;
                    hour = hour + 1;
                }
                ts = new TimeSpan(hour,minute, 0);
            }
            else 
            {
                if (time[1][3] == 'P')
                    hour += 12;
                int minute = Convert.ToInt16(time[1].Substring(0, 2)) +1;
                if (minute > 59)
                {
                    minute = 0;
                    hour = hour + 1;
                }
                ts = new TimeSpan(hour,minute, 0);
            }
            s = s.Date + ts;
            timeLbl.Text = s.ToShortTimeString();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.FormBorderStyle = FormBorderStyle.FixedDialog;

            insulinDoseOption.Font = new Font("Arial", 20);
            semiColon.Font = new Font("Arial", 20);
            hourSetting.Font = new Font("Arial", 20);
            minuteSetting.Font = new Font("Arial", 20);
            r0BloodLevel.Font = new Font("Arial", 20);

            r0BloodLevel.Text = "";
            r1BloodLevel.Text = "";
            r2BloodLevel.Text = "";
            lastInsulinDose.Text = "";
            totalInsulin.Text = "";
            insulinDoseOption.Text = "";
            labelNotify.Text = "";

            modeNameLbl.Text = modeBtn.Text;
            HideAllParam();
        }

        private void ReloadParam()
        {
            insulinDoseOption.Text = "";
            insulinDoseOption.Visible = false;

            semiColon.Visible = false;
            hourSetting.Visible = false;
            minuteSetting.Visible = false;

            r0BloodLevel.Text = "";
            r0BloodLevel.Visible = true;
            pictureBoxLevel.Visible = true;
            r1BloodLevel.Text = "";
            r1BloodLevel.Visible = true;
            r2BloodLevel.Text = "";
            r2BloodLevel.Visible = true;

            lastInsulinDose.Text = "";
            lastInsulinDose.Visible = true;
            totalInsulin.Text = "";
            totalInsulin.Visible = true;

            modeBtn.Text = "Auto";
            modeNameLbl.Text = modeBtn.Text;
            modeNameLbl.Visible = true;

            labelNotify.Text = "";
            labelNotify.Visible = true;

            timeLbl.Visible = true;

            batteryBar.Visible = true;
            pictureBoxLighting.Visible = true;
            batteryInfoLbl.Visible = true;

            remainInsulinBar.Visible = true;
            settingBtn.Enabled = true;

            StartTimer();

            chartBloodLevel.Visible = true;
            chartBloodLevel.Series[0].Points.Clear();
            for (int i = 29; i > -1; i--)
                chartBloodLevel.Series[0].Points.AddXY(i, 10);
        }
        
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i = 100; i >= 0; i--)
            {
                // Wait 100 milliseconds.
                Thread.Sleep(300000);
                // Report progress.
                backgroundWorker1.ReportProgress(i);
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            // Change the value of the ProgressBar to the BackgroundWorker progress.
            batteryBar.Value = e.ProgressPercentage;
            // Set the text.
            batteryInfoLbl.Text = e.ProgressPercentage.ToString() +"%";
        }

        private void settingBtn_Click(object sender, EventArgs e)
        {
            if (!flagTurnOn) // kiem tra dieu kien may da duoc len hay chua ??
                return;

            if (modeBtn.Text.Equals("Manual")) // kiem tr dieu kien neu may dang o
                return;                         // che do Manual thi k duoc thay doi dong ho

            if (flag) // kiem tra dieu huy bo thiet dat dong ho
            {
                settingBtn.Enabled = true;
                chartBloodLevel.Visible = true;
                r0BloodLevel.Visible = true;
                r1BloodLevel.Visible = true;
                r2BloodLevel.Visible = true;
                totalInsulin.Visible = true;
                lastInsulinDose.Visible = true;

                UpBtn.Enabled = false;
                pumpBtn.Enabled = false;
                downBtn.Enabled = false;
                hourSetting.Visible = false;
                minuteSetting.Visible = false;
                semiColon.Visible = false;
                flag = false;

                return;
            }

            flag = true;
            semiColon.Visible = true;
            hourSetting.Visible = true;
            minuteSetting.Visible = true;
            UpBtn.Enabled = true;
            downBtn.Enabled = true;
            pumpBtn.Enabled = true;

            hourSetting.Text = "0";
            minuteSetting.Text = "0";
            FocusedLabel = 0;

            chartBloodLevel.Visible = false;
            r0BloodLevel.Visible = false;
            r1BloodLevel.Visible = false;
            r2BloodLevel.Visible = false;
            totalInsulin.Visible = false;
            lastInsulinDose.Visible = false;

            hourSetting.BackColor = Color.LightGray;
            minuteSetting.BackColor = Color.White;
        }

        private void UpBtn_Click(object sender, EventArgs e)
        {
            if (FocusedLabel == 2)
            {
                insulinDoseOption.Text = (Convert.ToInt16(insulinDoseOption.Text) + 1).ToString();
                if (int.Parse(insulinDoseOption.Text) > 10)
                {
                    insulinDoseOption.Text = "0";

                }
            }
            else
            {
                if (FocusedLabel == 0)
                {
                    hourSetting.Text = (Convert.ToInt16(hourSetting.Text) + 1).ToString();
                    if (int.Parse(hourSetting.Text) > 24)
                    {
                        hourSetting.Text = "0";

                    }
                }
                else
                {
                    minuteSetting.Text = (Convert.ToInt16(minuteSetting.Text) + 1).ToString();
                    if (int.Parse(minuteSetting.Text) > 59)
                    {
                        minuteSetting.Text = "0";

                    }
                }
            }
        }

        private void pumpBtn_Click(object sender, EventArgs e)
        {
            if (flag) // dieu kien kiem tra button setting hay manual da duoc nhan
            {
                if (FocusedLabel != 0 && FocusedLabel != 1)
                {
                    FocusedLabel = 0;
                    hourSetting.BackColor = Color.LightGray;
                }
                else if (FocusedLabel == 0)
                {
                    FocusedLabel = 1;
                    hourSetting.BackColor = Color.White;
                    minuteSetting.BackColor = Color.LightGray;
                }
                else if (FocusedLabel == 1)
                {
                    settingBtn.Enabled = true;
                    chartBloodLevel.Visible = true;
                    r0BloodLevel.Visible = true;
                    r1BloodLevel.Visible = true;
                    r2BloodLevel.Visible = true;
                    totalInsulin.Visible = true;
                    lastInsulinDose.Visible = true;

                    UpBtn.Enabled = false;
                    pumpBtn.Enabled = false;
                    downBtn.Enabled = false;
                    hourSetting.Visible = false;
                    minuteSetting.Visible = false;
                    semiColon.Visible = false;
                    flag = false;

                    if (Convert.ToInt16(hourSetting.Text) <12)
                        timeLbl.Text = hourSetting.Text + ":" + minuteSetting.Text+" AM";
                    else
                        timeLbl.Text =(Convert.ToInt16(hourSetting.Text)-12).ToString() + ":" + minuteSetting.Text + " PM";
                }

            }
            else
            {
                FocusedLabel = -1;

                insulinDoseOption.Visible = false;
                UpBtn.Enabled = false;
                pumpBtn.Enabled = false;
                downBtn.Enabled = false;

                modeBtn.Text = "Auto";
                lastInsulinDose.Text = "Last Insulin Dose: " + insulinDoseOption.Text;
            }
        }

        private void downBtn_Click(object sender, EventArgs e)
        {
            if (FocusedLabel == 2)
            {
                insulinDoseOption.Text = (Convert.ToInt16(insulinDoseOption.Text) - 1).ToString();
                if (int.Parse(insulinDoseOption.Text) < 0)
                {
                    insulinDoseOption.Text = "0";
                    
                }
            }
            else
            {
                if (FocusedLabel == 0)
                {
                    hourSetting.Text = (Convert.ToInt16(hourSetting.Text) - 1).ToString();
                    if (int.Parse(hourSetting.Text) < 0)
                    {
                        hourSetting.Text = "23";

                    }
                }
                else
                {
                    minuteSetting.Text = (Convert.ToInt16(minuteSetting.Text) - 1).ToString();
                    if (int.Parse(minuteSetting.Text) < 0)
                    {
                        minuteSetting.Text = "59";

                    }
                }
            }
        }

        public void resetBtn_Click(object sender, EventArgs e)
        {
            if (buttonOnAndOff.Text.Equals("On")) // kiem tra may da duoc bat chua
                return;

            if (resetButtonClicked) // kiem tra dieu kien nhan lien tuc button reset
                return;

            resetButtonClicked = true;
            resetBtn.Enabled = false;
            buttonOnAndOff_Click(null, null);
        }

        private void HideAllParam()
        {
            r0BloodLevel.Visible = false;
            pictureBoxLevel.Visible = false;
            r1BloodLevel.Visible = false;
            r2BloodLevel.Visible = false;
            pumpBtn.Enabled = false;
            UpBtn.Enabled = false;
            downBtn.Enabled = false;
            lastInsulinDose.Visible = false;
            chartBloodLevel.Visible = false;
            totalInsulin.Visible = false;
            hourSetting.Visible = false;
            minuteSetting.Visible = false;
            semiColon.Visible = false;
            insulinDoseOption.Visible = false;
            FocusedLabel = -1;
            remainInsulinBar.Visible = false;
            batteryBar.Visible = false;
            pictureBoxLighting.Visible = false;
            batteryInfoLbl.Visible = false;
            modeNameLbl.Visible = false;
            timeLbl.Visible = false;
            labelNotify.Visible = false;
        }

        public void buttonOnAndOff_Click(object sender, EventArgs e)
        {
            if (buttonOnAndOff.Text.Equals("Off"))
            {
                groupBoxMainScreen.Enabled = false;
                groupBoxMainScreen.BackColor = Color.Gray;
                buttonOnAndOff.Text = "On";
                HideAllParam();
                flagTurnOn = false;

            }
            else
            {
                ReloadParam();
                groupBoxMainScreen.Enabled = true;
                groupBoxMainScreen.BackColor = Color.LightBlue;
                flagTurnOn = true;
                buttonOnAndOff.Text = "Off";
                Thread.Sleep(1000);
                if (!pumpControllerThread.IsAlive)
                    pumpControllerThread.Start();
                Thread.Sleep(500);
                if (!testerThread.IsAlive)
                    testerThread.Start();
            }
        }

        public void addNotify(string message, int type)
        {
            labelNotify.Text = message;
            if (type != NORMAL)
            {
                if (type == WARNING)
                {
                    labelNotify.ForeColor = Color.Orange;
                    Console.Beep();
                }
                else
                {
                    labelNotify.ForeColor = Color.Red;
                    System.Media.SystemSounds.Hand.Play();
                }
            }
            else
                labelNotify.Text = "";
        }

        public void UpdateScreen(int remainInsulin, int insulinDose, int totalInsulinDose,float bloodLevel)
        {
            if (chartBloodLevel.Series[0].Points.Count < 30)
            {
                    chartBloodLevel.Series[0].Points.AddXY(30 - chartBloodLevel.Series[0].Points.Count, bloodLevel);
            }
            else
            {
                for (int i = 29; i > 0; i--)
                {
                   
                    chartBloodLevel.Series[0].Points[i].YValues[0] = chartBloodLevel.Series[0].Points[i - 1].YValues[0];
                }

                double[] b = { bloodLevel };
                chartBloodLevel.Series[0].Points[0].YValues = b;
            }

            this.remainInsulinBar.Value = remainInsulin;
            this.totalInsulin.Text = "Total Daily Dose: " + totalInsulinDose.ToString();
            this.lastInsulinDose.Text = "Last Insulin Dose: " + insulinDose.ToString();

            this.r2BloodLevel.Text = this.r1BloodLevel.Text;
            this.r1BloodLevel.Text = this.r0BloodLevel.Text;
            this.r0BloodLevel.Text =bloodLevel.ToString();

            double r0;
            if (r0BloodLevel.Text.Equals(""))
                r0 = 0;
            else
                r0 = Convert.ToDouble(r0BloodLevel.Text);

            double r1;
            if (r1BloodLevel.Text.Equals(""))
                r1 = 0;
            else
                r1 = Convert.ToDouble(r1BloodLevel.Text);

            if ((r0 - r1) > 0)
            {
                this.pictureBoxLevel.Image = ASS2_CNPM_2014.Properties.Resources.uparrow;
            }
            else
            {
                this.pictureBoxLevel.Image = ASS2_CNPM_2014.Properties.Resources.downarrow;

            }
            this.Update();
        }

        private void MainInterface_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (pumpControllerThread.IsAlive && !resetButtonClicked)
                pumpControllerThread.Abort();

            if (testerThread.IsAlive && !resetButtonClicked)
                testerThread.Abort();
        }       
    }
}
